package com.example.flowerpcback.controller;

import com.example.flowerpcback.dto.Roles;
import com.example.flowerpcback.dto.User;
import com.example.flowerpcback.req.RolesReq;
import com.example.flowerpcback.req.UserReq;
import com.example.flowerpcback.resp.CommonResp;
import com.example.flowerpcback.resp.PageResp;
import com.example.flowerpcback.resp.RolesResp;
import com.example.flowerpcback.resp.UserResp;
import com.example.flowerpcback.services.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;


@RestController //这是返回接口
@RequestMapping("/user")
public class UserController {

    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;


    @PostMapping("/login")
    public CommonResp<UserResp> login(@Valid @RequestBody UserReq req){
        req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        CommonResp resp= new CommonResp<>();

        UserResp user = userService.login(req,req.getSessionId());
        resp.setData(user);
        return  resp;
    }

    @PostMapping("/logout")
    public CommonResp<UserResp> logout(@Valid @RequestBody String token){
        CommonResp resp= new CommonResp<>();
        userService.logout(token);
        return  resp;
    }

    @GetMapping("/list")
    public CommonResp<PageResp<UserResp>> list(@Valid UserReq req){
        CommonResp<PageResp<UserResp>> resp= new CommonResp<>();
        PageResp<UserResp> userRespList = userService.list(req);
        resp.setData(userRespList);
        return  resp;
    }

    @GetMapping("/myList")
    public CommonResp<PageResp<UserResp>> myList(@Valid UserReq req){
        CommonResp<PageResp<UserResp>> resp= new CommonResp<>();
        PageResp<UserResp> userRespList = userService.myList(req);
        resp.setData(userRespList);
        return  resp;
    }

    @PostMapping("/save")
    public CommonResp<User> save(@Valid @RequestBody UserReq req){
        if(req.getPassword()!=null){
            req.setPassword(DigestUtils.md5DigestAsHex(req.getPassword().getBytes()));
        }
        CommonResp<User> resp= new CommonResp<>();
        User user = userService.save(req);
        resp.setData(user);
        return resp;
    }

    @GetMapping("/delete")
    public CommonResp delete(@Valid UserReq req){
        CommonResp resp= new CommonResp<>();
        userService.delete(req);
        return  resp;
    }
}

